package com.example.library.view;

import android.app.Activity;
import android.content.Context;
import android.content.res.TypedArray;
import android.graphics.Color;
import android.support.v4.app.FragmentManager;
import android.support.v7.widget.AppCompatTextView;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.TextPaint;
import android.text.TextUtils;
import android.text.method.LinkMovementMethod;
import android.text.style.BackgroundColorSpan;
import android.text.style.ClickableSpan;
import android.text.style.ForegroundColorSpan;
import android.text.style.UnderlineSpan;
import android.util.AttributeSet;
import android.view.MotionEvent;
import android.view.View;
import android.widget.TextView;
import android.widget.Toast;

import com.example.library.R;
import com.example.library.RequestBack;
import com.example.library.RequestKnowledgeEntity;
import com.example.library.RequestKnowledgeParseEntity;
import com.example.library.dialog.KnowLedgeAnalysisDialog;
import com.example.library.http.KnowledgeEntity;
import com.example.library.http.KnowledgeParseEntity;
import com.example.library.viewmodle.CheckWordDialogViewModel;

import java.util.ArrayList;
import java.util.List;

/**
 * Created by dadong on 2018/8/14.
 * Describe: any suggestion pls email 17826875948@163.com
 */

public class CheckWordTextView extends AppCompatTextView {

    private CharSequence mText;
    private BufferType mBufferType;

    private OnWordClickListener mOnWordClickListener;
    private SpannableString mSpannableString;
    FragmentManager fragmentManager;

    private BackgroundColorSpan mSelectedBackSpan;
    private ForegroundColorSpan mSelectedForeSpan;
    private Activity mACtivity;
    private KnowLedgeAnalysisDialog mDialog;

    private int highlightColor;
    private String highlightText;
    private String[] highlightTexts = {};
    private int selectedColor;
    private int language;//0:english,1:chinese
    private int selectedTextColor;
    float[] position = {-1, -1};
    private Toast toast;
    private boolean onlyClickHighlightText = false;
    String schoolId;
    String stageNo;
    String stuId;

    List<KnowledgeEntity> knowledgeEntitys = new ArrayList<>();

    //请求网络数据
    RequestKnowledgeParseEntity requestKnowLedgeParseEntity;
    RequestBack<KnowledgeParseEntity> mRequestCall;

    public CheckWordTextView(Context context) {
        this(context, null);
    }

    public CheckWordTextView(Context context, AttributeSet attrs) {
        this(context, attrs, 0);
    }

    public CheckWordTextView(Context context, AttributeSet attrs, int defStyleAttr) {
        super(context, attrs, defStyleAttr);
        TypedArray ta = context.obtainStyledAttributes(attrs, R.styleable.CheckWordTextView);
        highlightColor = ta.getColor(R.styleable.CheckWordTextView_highlightColor, Color.RED);
        highlightText = ta.getString(R.styleable.CheckWordTextView_highlightText);
        selectedColor = ta.getColor(R.styleable.CheckWordTextView_selectedColor, Color.BLUE);
        language = ta.getInt(R.styleable.CheckWordTextView_language, 0);
        selectedTextColor = ta.getColor(R.styleable.CheckWordTextView_selectedTextColor, Color.WHITE);
        onlyClickHighlightText = ta.getBoolean(R.styleable.CheckWordTextView_onlyClickHighlightText, false);
        ta.recycle();
    }

    private CheckWordDialogViewModel getViewModel(KnowledgeParseEntity knowledgeParseEntity) {
        CheckWordDialogViewModel viewModel = new CheckWordDialogViewModel();
        return NewDealDataUtil.getViewModel(viewModel, knowledgeParseEntity);
    }

    @Override
    public void setText(CharSequence text, BufferType type) {
        mRequestCall = new RequestBack<KnowledgeParseEntity>() {
            @Override
            public void onSuccess(KnowledgeParseEntity knowledgeParseEntity) {
                if (mACtivity != null) {
                    showmDialog(getViewModel(knowledgeParseEntity));
                }
            }

            @Override
            public void onErr(Throwable e) {

            }
        };
        requestKnowLedgeParseEntity = new RequestKnowledgeParseEntity(mACtivity, mRequestCall);
        this.mText = text;
        mBufferType = type;
        setHighlightColor(Color.TRANSPARENT);
        setMovementMethod(LinkMovementMethod.getInstance());
        setText();
    }

    private void setText() {
        mSpannableString = new SpannableString(mText);
        if (onlyClickHighlightText) {
            if (language == 0) {
                setOnlyClickHighlightText(mSpannableString);
            } else {
                // TODO: 2018/8/15 暂时只支持英语
            }
        } else {
            setHighLightSpan(mSpannableString);
            if (language == 0) {//deal english
                dealEnglish();
            } else {//deal chinese
                dealChinese();
            }
        }
        super.setText(mSpannableString, mBufferType);
    }

    private void dealChinese() {
        for (int i = 0; i < mText.length(); i++) {
            char ch = mText.charAt(i);
            if (Utils.isChinese(ch)) {
                mSpannableString.setSpan(getClickableSpan(), i, i + 1, Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            }
        }
    }

    private void dealEnglish() {
        List<WordInfo> wordInfoList = Utils.getEnglishWordIndices(mText.toString());
        for (WordInfo wordInfo : wordInfoList) {
            mSpannableString.setSpan(getClickableSpan(), wordInfo.getStart(), wordInfo.getEnd(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        }
    }

    private void setHighLightSpan(SpannableString spannableString) {
        if (TextUtils.isEmpty(highlightText)) {
            return;
        }

        int hIndex = mText.toString().indexOf(highlightText);

        while (hIndex != -1) {
            spannableString.setSpan(new ForegroundColorSpan(highlightColor), hIndex, hIndex + highlightText.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
            hIndex += highlightText.length();
            hIndex = mText.toString().indexOf(highlightText, hIndex);
        }
    }

    private void setOnlyClickHighlightText(SpannableString spannableString) {
        if (highlightTexts.length > 0) {
            for (int i = 0; i < highlightTexts.length; ++i) {
                if (TextUtils.isEmpty(highlightTexts[i])) {
                    return;
                }
                int hIndex = mText.toString().indexOf(highlightTexts[i]);
                while (hIndex != -1) {
                    List<WordInfo> wordInfoList = Utils.getEnglishWordIndices(mText.toString());
                    for (WordInfo wordInfo : wordInfoList) {
                        if (hIndex == wordInfo.getStart() && (hIndex + highlightTexts[i].length()) == wordInfo.getEnd()) {
                            spannableString.setSpan(new UnderlineSpan(), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(new ForegroundColorSpan(highlightColor), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(getClickableSpan(), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                    if (hIndex - 1 >= 0) {
                        if (judge(spannableString.charAt(hIndex - 1), spannableString.charAt(hIndex + highlightTexts[i].length() - 1))) {
                            spannableString.setSpan(new UnderlineSpan(), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(new ForegroundColorSpan(highlightColor), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(getClickableSpan(), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                    if (hIndex == 0) {
                        if (spannableString.charAt(hIndex + highlightTexts[i].length()) == 10) {
                            spannableString.setSpan(new UnderlineSpan(), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(new ForegroundColorSpan(highlightColor), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                            spannableString.setSpan(getClickableSpan(), hIndex, hIndex + highlightTexts[i].length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
                        }
                    }
                    hIndex += highlightTexts[i].length();
                    hIndex = mText.toString().indexOf(highlightTexts[i], hIndex);
                }
            }
        }
    }

    /**
     * 处理换行符 10是换行符的ascii码
     *
     * @param start
     * @param end
     * @return
     */
    private boolean judge(char start, char end) {
        if ((start == 10 && end == 10) || (start == 10 && end == 32)) {
            return true;
        }
        return false;
    }

    private void setSelectedSpan(TextView tv) {
        if (mSelectedBackSpan == null || mSelectedForeSpan == null) {
            mSelectedBackSpan = new BackgroundColorSpan(selectedColor);
            mSelectedForeSpan = new ForegroundColorSpan(selectedTextColor);
        } else {
            mSpannableString.removeSpan(mSelectedBackSpan);
            mSpannableString.removeSpan(mSelectedForeSpan);
        }
        mSpannableString.setSpan(mSelectedBackSpan, tv.getSelectionStart(), tv.getSelectionEnd(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        mSpannableString.setSpan(mSelectedForeSpan, tv.getSelectionStart(), tv.getSelectionEnd(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        CheckWordTextView.super.setText(mSpannableString, mBufferType);
    }

    public void dismissSelected() {
        mSpannableString.removeSpan(mSelectedBackSpan);
        mSpannableString.removeSpan(mSelectedForeSpan);
        CheckWordTextView.super.setText(mSpannableString, mBufferType);
    }

    private ClickableSpan getClickableSpan() {
        return new ClickableSpan() {
            @Override
            public void onClick(View widget) {
                TextView tv = (TextView) widget;
                int startIndex = tv.getSelectionStart();
                int endIndex = tv.getSelectionEnd();
                if (TextUtils.isEmpty(getText()) || startIndex == -1 || endIndex == -1) {
                    return;
                }

                String word = tv
                        .getText()
                        .subSequence(startIndex,
                                endIndex).toString();
                setSelectedSpan(tv);

                if (mOnWordClickListener != null) {
                    mOnWordClickListener.onClick(word);
                }
                //请求网络，获取解析结果
                for (int i = 0; i < knowledgeEntitys.size(); ++i) {
                    if (word.trim().equals(knowledgeEntitys.get(i).getZSDNameInText().trim())) {
//                        requestKnowLedgeParseEntity.getData(word, "B");
                        requestKnowLedgeParseEntity.getData(knowledgeEntitys.get(i).getZSDCode(), "B", schoolId, stageNo, stuId);
                        return;
                    }
                }
            }

            @Override
            public void updateDrawState(TextPaint ds) {
            }
        };
    }

    public void setmACtivity(Activity activity, FragmentManager fragmentManager,String schoolId, String stageNo, String stuId) {
        this.mACtivity = activity;
        this.fragmentManager = fragmentManager;
//        this.token = token;
        this.schoolId = schoolId;
        this.stageNo = stageNo;
        this.stuId = stuId;
    }


    public void setOnWordClickListener(OnWordClickListener listener) {
        this.mOnWordClickListener = listener;
    }

    /**
     * Notice: code before TextView.setText().
     *
     * @param texts
     */
    public void setHighLightTexts(String[] texts) {
        this.highlightTexts = texts;
    }

    public void setKnowledgeEntitys(List<KnowledgeEntity> knowledgeEntitys) {
        this.knowledgeEntitys.addAll(knowledgeEntitys);
        String[] highlightTexts = new String[knowledgeEntitys.size()];
        for (int i = 0; i < knowledgeEntitys.size(); ++i) {
            highlightTexts[i] = knowledgeEntitys.get(i).getZSDNameInText();
        }
        setHighLightTexts(highlightTexts);
    }

    public void setHighLightColor(int color) {
        this.highlightColor = color;
    }

    public interface OnWordClickListener {
        void onClick(String word);
    }

    public void showToast(String msg) {
        if (toast == null) {
            toast = Toast.makeText(getContext(), msg, Toast.LENGTH_SHORT);
        }
        toast.setText(msg);
        toast.show();
    }

    private void showmDialog(CheckWordDialogViewModel viewModel) {
        mDialog = new KnowLedgeAnalysisDialog();
        mDialog.setMViewModel(viewModel);

        mDialog.show(fragmentManager);
    }

    /**
     * @return 点击的坐标
     */
    public float[] getposition() {
        CheckWordTextView.this.setOnTouchListener(new OnTouchListener() {
            @Override
            public boolean onTouch(View v, MotionEvent event) {
                // showToast(event.getX() + "  " + event.getY());
                position[0] = event.getX();
                position[1] = event.getY();
                return false;
            }
        });
        return position;
    }


}
